package com.gview.example.common.services.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import com.gonsin.base.GPageRequest;
import com.gonsin.base.GPageResult;
import com.gonsin.gview.annotations.actions.GAction;
import com.gonsin.gview.annotations.data.GDataChanged;
import com.gonsin.gview.annotations.data.GDataSource;
import com.gview.example.common.bean.BookBean;
import com.gview.example.common.po.BookSearchPo;
import com.gview.example.common.services.IBookService;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class BookServiceImpl implements IBookService {

    private List<BookBean> data = new ArrayList<>();

    @Override
    @GAction("addBook")
    @GDataChanged("searchBook")
    public BookBean addBook(BookBean book) {
        book.setBookKey(RandomStringUtils.random(32, true, true));
        data.add(book);
        return book;
    }

    @Override
    @GAction("updateBook")
    @GDataChanged("searchBook")
    public BookBean updateBook(BookBean book) {
        data.stream().filter(b -> b.getBookKey().equals(book.getBookKey())).findFirst().ifPresent(b -> {
            BeanUtil.copyProperties(book, b, CopyOptions.create().setIgnoreNullValue(true));
        });
        return book;
    }

    @Override
    @GDataSource("searchBook")
    public GPageResult<BookBean> searchBook(BookSearchPo searchPo, GPageRequest request) {
        int first = request.getCount() * request.getPage();
        int last = Math.min(first + request.getCount(), data.size());
        List<BookBean> list = new ArrayList<>();
        if(last > 0){
            for(int i = first; i < last; i++){
                list.add(data.get(i));
            }
        }
        return GPageResult.result(list, data.size(), request);
    }

    @Override
    @GAction("batchDeleteBook")
    @GDataChanged("searchBook")
    public void batchDeleteBook(List<String> bookKeys) {
        for(String key : bookKeys){
            data.removeIf(b -> b.getBookKey().equals(key));
        }
    }

    @Override
    @GAction("deleteBook")
    @GDataChanged("searchBook")
    public void deleteBook(String bookKey) {
        data.removeIf(b -> b.getBookKey().equals(bookKey));
    }

    @Override
    @GDataSource("getBook")
    public BookBean getBook(String bookKey) {
        return data.stream().filter(b -> b.getBookKey().equals(bookKey)).findFirst().get();
    }
}
